<?php
namespace App\Api\Controllers\Cmbc;

use App\Api\Controllers\Config\VbillConfigController;
use App\Models\YinkaStore;
use Illuminate\Support\Facades\Log;
use App\Api\Controllers\Cmbc\BaseController as base;
use function EasyWeChat\Kernel\Support\get_client_ip;
class PayController extends BaseController
{

    function get_millisecond(){
        list($usec, $sec) = explode(" ", microtime());
        $msec=round($usec*1000);
        return date('YmdHis', time()).$msec;
    }
    public function scan_pay($data, $config)
    {
        try {
            $params = [
                "platformId" => $config->platform_id,
                "merchantNo" => $data['mch_id'],
                "merchantSeq" => $data['out_trade_no'],
                "mchSeqNo" => $data['out_trade_no'],
                "selectTradeType" => $data['select_trade_type'],
                "amount" => number_format($data['total_amount'] * 100, 0, '.', ''),
                "orderInfo" => "统一下单",
//                "notifyUrl" => "",
                "remark" => base64_encode($data['code']),
                "transDate" => date('Ymd'),
                "transTime" => $this->get_millisecond(),
//                "inExtData" => "测试请求扩展大字段",
//                "deviceInfo" => "123456"
            ];
            $base64CertData = file_get_contents(app_path('Api/Controllers/Cmbc/' . $config->cert_path));
            $cert = [
                'base64P12Data' => $data['private_key'],
                'P12Password' => '123abc',
                'base64P12SignAlg' => 'SM3withSM2',
                'base64CertData' => $base64CertData,
                'base64CertSignAlg' => 'SM4/CBC/PKCS7Padding',
                'apiPath' => $config->api_path
            ];

            $base = base::getInstance();
            error_log(date('Y-m-d H:i:s')." 【民生被扫入参】： ".json_encode([$params])."\n\n", 3, "/tmp/". 'cmbc'.date('Ymd').".log");
            $ret  = $base->params($params, $cert)->build($cert, $base::MIAN);
            error_log(date('Y-m-d H:i:s')." 【民生被扫出参】： ".json_encode([$ret])."\n\n", 3, "/tmp/". 'cmbc'.date('Ymd').".log");

            if ($ret['status'] == 1) {
                //R 原订单成功，未支付（待支付）
                //S 订单成功
                if ($ret['data']['tradeStatus'] == 'S') { //支付成功
                    return [
                        'status' => 1,
                        'message' => '支付成功',
                        'data' => $ret['data']
                    ];
                }
                if ($ret['data']['tradeStatus'] == 'E') { //支付失败
                    return [
                        'status' => 3,
                        'message' => '订单失败',
                    ];
                }
                return [
                    'status' => 2,
                    'message' => '支付中',
                ];
            } else {
                return [
                    'status' => 3,
                    'message' => $ret['message'],
                ];
            }
        } catch (\Exception $ex) {
            return [
                'status' => 3,
                'message' => $ex->getMessage().' | '.$ex->getFile().' | '.$ex->getLine(),
            ];
        }
    }


    //查询订单 0-系统错误 1-成功 2-正在支付 3-失败 4.已经退款

    public function order_query($data, $config)
    {
        try {
            $params = [
                "platformId" => $config->platform_id,
                "merchantNo" => $data['mch_id'],
                "merchantSeq" => $data['out_trade_no'],
                'tradeType' => 1,
            ];
            $base64CertData = file_get_contents(app_path('Api/Controllers/Cmbc/' . $config->cert_path));
            $cert = [
                'base64P12Data' => $data['private_key'],
                'P12Password' => '123abc',
                'base64P12SignAlg' => 'SM3withSM2',
                'base64CertData' => $base64CertData,
                'base64CertSignAlg' => 'SM4/CBC/PKCS7Padding',
                'apiPath' => $config->api_path
            ];
            $base = base::getInstance();
            error_log(date('Y-m-d H:i:s')." 【民生查询入参】： ".json_encode([$params])."\n\n", 3, "/tmp/". 'cmbc'.date('Ymd').".log");
            $ret  = $base->params($params, $cert)->build($cert, $base::ORDER_QUERY);
            error_log(date('Y-m-d H:i:s')." 【民生查询出参】： ".json_encode([$ret])."\n\n", 3, "/tmp/". 'cmbc'.date('Ymd').".log");

            if ($ret['status'] == 1) {
                //R 原订单成功，未支付（待支付）
                //S 订单成功
                if ($ret['data']['tradeStatus'] == 'S') { //支付成功
                    return [
                        'status' => 1,
                        'message' => '支付成功',
                        'data' => $ret['data']
                    ];
                }
                if ($ret['data']['tradeStatus'] == 'E') { //支付失败
                    return [
                        'status' => 3,
                        'message' => '订单失败',
                    ];
                }
                return [
                    'status' => 2,
                    'message' => '支付中',
                ];
            } else {
                return [
                    'status' => 3,
                    'message' => $ret['message'],
                ];
            }
        } catch (\Exception $ex) {
            return [
                'status' => '0',
                'message' => $ex->getMessage().' | '.$ex->getFile().' | '.$ex->getLine(),
            ];
        }
    }


    //退款 0-系统错误 1-成功
    public function refund($data, $config)
    {
        try {
            $params = [
                "platformId" => $config->platform_id,
                "merchantNo" => $data['mch_id'],
                "merchantSeq" => $data['out_trade_no'],
                "mchSeqNo" => $data['refund_no'],
                'orderAmount' => number_format($data['refund_amount'] * 100, 0, '.', ''),
            ];
            $base64CertData = file_get_contents(app_path('Api/Controllers/Cmbc/' . $config->cert_path));
            $cert = [
                'base64P12Data' => $data['private_key'],
                'P12Password' => '123abc',
                'base64P12SignAlg' => 'SM3withSM2',
                'base64CertData' => $base64CertData,
                'base64CertSignAlg' => 'SM4/CBC/PKCS7Padding',
                'apiPath' => $config->api_path
            ];
            $base = base::getInstance();
            error_log(date('Y-m-d H:i:s')." 【民生退款入参】： ".json_encode([$params])."\n\n", 3, "/tmp/". 'cmbc'.date('Ymd').".log");
            $ret  = $base->params($params, $cert)->build($cert, $base::REFUND);
            error_log(date('Y-m-d H:i:s')." 【民生退款出参】： ".json_encode([$ret])."\n\n", 3, "/tmp/". 'cmbc'.date('Ymd').".log");

            if ($ret['status'] == 1) {
                //R 原订单成功，未支付（待支付）
                //S 订单成功
                if ($ret['data']['tradeStatus'] == 'S') { //支付成功
                    return [
                        'status' => 1,
                        'message' => '退款成功',
                        'data' => $ret['data']
                    ];
                }
                if ($ret['data']['tradeStatus'] == 'E') { //支付失败
                    return [
                        'status' => 3,
                        'message' => '退款失败',
                    ];
                }
                return [
                    'status' => 3,
                    'message' => '退款失败',
                ];
            } else {
                return [
                    'status' => 3,
                    'message' => $ret['message'],
                ];
            }
        } catch (\Exception $ex) {
            return [
                'status' => 0,
                'message' => $ex->getMessage().' | '.$ex->getFile().' | '.$ex->getLine()
            ];
        }
    }


    //退款查询 0-系统错误 1-成功 2-正在退款 3-失败
    public function refund_query($data)
    {
        try {


        } catch (\Exception $ex) {
            return [
                'status' => '0',
                'message' => $ex->getMessage().' | '.$ex->getFile().' | '.$ex->getLine()
            ];
        }
    }


    public function qr_submit ($data, $config)
    {
        try {
            $params = [
                "platformId" => $config->platform_id,
                "merchantNo" => $data['mch_id'],
                "merchantSeq" => $data['out_trade_no'],
                "mchSeqNo" => $data['out_trade_no'],
                "selectTradeType" => $data['select_trade_type'],
                "amount" => number_format($data['total_amount'] * 100, 0, '.', ''),
                "orderInfo" => "扫码下单",
                "notifyUrl" => '11'.$data['notifyUrl'],
                "transDate" => date('Ymd'),
                "transTime" => $this->get_millisecond(),
//                "inExtData" => "测试请求扩展大字段",
//                "deviceInfo" => "123456"
            ];
            $base64CertData = file_get_contents(app_path('Api/Controllers/Cmbc/' . $config->cert_path));
            $cert = [
                'base64P12Data' => $data['private_key'],
                'P12Password' => '123abc',
                'base64P12SignAlg' => 'SM3withSM2',
                'base64CertData' => $base64CertData,
                'base64CertSignAlg' => 'SM4/CBC/PKCS7Padding',
                'apiPath' => $config->api_path
            ];

            $base = base::getInstance();
            error_log(date('Y-m-d H:i:s')." 【民生主扫扫入参】： ".json_encode([$params])."\n\n", 3, "/tmp/". 'cmbc'.date('Ymd').".log");
            $ret  = $base->params($params, $cert)->build($cert, $base::MIAN);
            error_log(date('Y-m-d H:i:s')." 【民生主扫出参】： ".json_encode([$ret])."\n\n", 3, "/tmp/". 'cmbc'.date('Ymd').".log");

            if ($ret['status'] == 1) {
                $codeUrl = base64_decode($ret['data']['payInfo']);
//                if ($data['select_trade_type'] == 'API_WXQRCODE' || $data['select_trade_type'] == 'API_UNIONQRCODE') {
//                    $codeUrl = 'https://wxpay.cmbc.com.cn/mobilePlatform/union/cmbcRedirect.do?qrCode='.base64_decode($ret['data']['payInfo']);
//                } else {
//                    $codeUrl = explode('=', $ret['data']['remark']);
//                    $codeUrl = explode('|', $codeUrl[1]);
//                    $codeUrl = $codeUrl[0];
//                }
//                if ($data['select_trade_type'] == 'API_ZFBQRCODE') {
//                    $codeUrl = explode('=', $ret['data']['remark']);
//                    $codeUrl = explode('|', $codeUrl[1]);
//                    $codeUrl = $codeUrl[0];
//                }
//                $codeUrl = explode('=', $ret['data']['remark']);
//                $codeUrl = explode('|', $codeUrl[1]);
//                $codeUrl = $codeUrl[0];
                return [
                    'status' => 1,
                    'message' => '',
                    'data' => [
                        'codeUrl' => $codeUrl
                    ]
                ];
            } else {
                return [
                    'status' => 3,
                    'message' => $ret['message'],
                ];
            }
        } catch (\Exception $ex) {
            return [
                'status' => 3,
                'message' => $ex->getMessage().' | '.$ex->getFile().' | '.$ex->getLine(),
            ];
        }
    }





}
